import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'main.dart';

class CaseDialog {
  final GlobalKey webViewKey = GlobalKey();
  void build1(
    BuildContext context,
    String word,
  ) {
    ButtonLay buttonLay = ButtonLay(0, word);
    int favIndex = 0;

    InAppWebViewController? webViewController;
    showDialog(
        context: context,
        builder: (_) => Padding(
              padding:
                  EdgeInsets.only(top: 40, left: 20, right: 20, bottom: 120),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Scaffold(
                  //Material组件
                  body: Container(
                    color: Colors.white,
                    child: Column(children: <Widget>[
                      Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(word, style: TextStyle(fontSize: 20)),
                            Container(
                              width: 10,
                            ),
                            buttonLay,
                          ]),
                      Expanded(
                          child: InAppWebView(
                        key: webViewKey,
                        initialUrlRequest: URLRequest(
                            url: Uri.parse(
                                "https://www.iciba.com/word?w=" + word)),
                        onWebViewCreated: (controller) {
                          webViewController = controller;
                        },
                        onLoadStop: (controller, url) {
                          print("onLoadStop");

                          webViewController
                              ?.evaluateJavascript(
                                  source:
                                      'var description = document.getElementsByClassName(\'dic-recommend\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'dic-nav-tab\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'dic-nav-tab\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'dic-info\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'dic-bottom-list\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'dic-bottom-btn\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'dic-follow\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementsByClassName(\'index-main\')[0];'
                                      'description.parentNode.removeChild(description);'
                                      'var description = document.getElementById(\'nav\');'
                                      'description.parentNode.removeChild(description);'


                                          //删除展开双语搭配按钮
                                          'var description = document.getElementsByClassName(\'dic-more\')[1];'
                                          'description.parentNode.removeChild(description);'

                                          //删除展开双语例句按钮
                                          'var description = document.getElementsByClassName(\'dic-more\')[0];'
                                          'description.parentNode.removeChild(description);'

                                      //自动展开固定搭配
                                          'document.getElementsByClassName(\'dic-double dic-less\')[1].setAttribute(\'class\',\'dic-double\');'
                                      //自动展开例句
                                          'document.getElementsByClassName(\'dic-double dic-less\')[0].setAttribute(\'class\',\'dic-double\');'
                                      //去掉头部空白
                                      'document.getElementsByClassName(\'result result-transition\')[0].setAttribute(\'class\',\'result-transition\');'

                                      //删除跟读按钮
                                          'var description = document.getElementsByClassName(\'dic-basic-voice\')[0].getElementsByTagName(\'img\')[0];'
                                          'description.parentNode.removeChild(description);'

                                  )
                              .then((value2) {
                            print("shiyia");
                            print(value2);
                          });

                          daoCase.getWordByWord(word).then((data) {

                            for (int i = 0; i < data.length; i++) {
                              print("getWordByWord");
                              print(data);
                              favIndex = data[i]['_favorite'] as int;
                              print("favIndex");
                              print(favIndex);
                              buttonLay.reload(favIndex);
                            }


                            if (data.isEmpty) {
                              webViewController
                                  ?.evaluateJavascript(
                                  source:
                                  'document.getElementsByClassName(\'dic-basic-explain\')[0].innerText;')
                                  .then((value2) {
                                print("shiyiasd123");
                                // print(value2.toString().split("\n"));
                                List<String> means =
                                value2.toString().split("\n");
                                String mean = means[0] + " " + means[1];
                                for (int i = 2; i < means.length; i++) {
                                  mean =
                                      mean + "\n" + means[i] + " " + means[i + 1];
                                  i++;
                                }

                                webViewController
                                    ?.evaluateJavascript(
                                    source:
                                    'document.getElementsByClassName(\'dic-basic-voice\')[0].innerText;')
                                    .then((value1) {
                                  String voice =
                                  value1.toString().replaceAll("\n", ", ");

                                  daoCase
                                      .insertCase(word, mean, voice)
                                      .then((data) {
                                    print('插入成功            %%%%%%%%%');
                                  }).catchError((err) {
                                    print('%插入失败            %%%%%%%%%');
                                  });
                                });
                              });
                            }
                          }).catchError((err) {
                            print('daoCasehhj___');
                            print(err);
                            print('___');
                          });


                        },
                      )),
                    ]),
                  ),
                ),
              ),
            ));
  }
}

class ButtonLay extends StatefulWidget {
  late int butIndex;
  String word;
  void reload(int name) {
    caseNameLayout.reload(name);
  }

  ButtonLay(this.butIndex, this.word);

  ButtonLayout caseNameLayout = ButtonLayout();

  @override
  State<StatefulWidget> createState() {
    caseNameLayout.setCaseNameTitle(this.butIndex, this.word);
    return caseNameLayout;
  }
}

class ButtonLayout extends State<ButtonLay> {
  late int butIndex;
  late String word;

  List iconList = [Icons.favorite_outline_sharp, Icons.favorite_outlined];
  void setCaseNameTitle(int name, String w) {
    word = w;
    butIndex = name;
  }

  void reload(int index) {
    butIndex = index;
    setState(() {});
  }

  //
  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(iconList[butIndex]),
      onPressed: () {
        int tmp = 1 - butIndex;
        reload(tmp);

        daoCase.updateByWord(word, tmp).then((data) {
          print('xiugai成功            %%%%%%%%%');
        }).catchError((err) {
          print('%xiugai失败            %%%%%%%%%');
          print(err);
        });
      },
    );
  }
}
